﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Globalization;

namespace PhineClient
{
    public class Client
    {

        string url = @"http://localhost:8811/";
        public string Response = string.Empty;
        
        
        public void connect(ref string message, string constring)
        {
            var webClient = new WebClient();
            string junk = "^"+DateTime.Now.Second.ToString(CultureInfo.CurrentCulture);
            Uri uri = new Uri(constring + message+junk);
            webClient.OpenReadAsync(uri);
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            var result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
            message = Response; 
        }

        private void ResponseCallback(IAsyncResult result)
        {
            var request = (HttpWebRequest)result.AsyncState;
            var response = request.EndGetResponse(result);

            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var contents = reader.ReadToEnd();
                Response = contents;
            }
        }


        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            using (var reader = new StreamReader(e.Result))
            {
                Response = reader.ReadToEnd();
            }
        }
    }
}
